﻿_Widget = function(element, Tab)
{
   this.obj = element;
   if (this.obj.Icon && this.obj.Icon.length > 0)
   {
   }
   else
   {
      //no icon or empty icon url
      this.obj.Icon = "/widgets/default.gif";
   }
   this.id = element.id;
   this.loaded = false;
   this.Tab = Tab;
   this.code = "";
}

_Widget.prototype =
{
    ToString: function() {
        var str = "";
        str += "id : " + this.id + "\n";
        str += "loaded : " + this.loaded + "\n";
        str += "Tab : " + this.Tab + "\n";
        str += "obj.id : " + this.obj.id + "\n";
        str += "obj.ColumnNo : " + this.obj.ColumnNo + "\n";
        str += "obj.OrderNo : " + this.obj.OrderNo + "\n";
        str += "obj.Expanded : " + this.obj.Expanded + "\n";
        str += "obj.Title : " + this.obj.Title + "\n";
        str += "obj.URL : " + this.obj.URL + "\n";
        str += "obj.Icon : " + this.obj.Icon + "\n";
        str += "obj.State : " + this.obj.State + "\n";
        str += "Tab.Element_Widgets : " + this.Tab.Element_Widgets.id + "\n";
        str += "Tab.Element_Cell1 : " + this.Tab.Element_Cell1.id + "\n";
        str += "Tab.Element_Cell2 : " + this.Tab.Element_Cell2.id + "\n";
        str += "Tab.Element_Cell3 : " + this.Tab.Element_Cell3.id + "\n";
        if (this.Tab.Element_Cell4)
            str += "Tab.Element_Cell4 : " + this.Tab.Element_Cell4.id + "\n";
        str += "Instance : " + this.instance + "\n";
        str += "Height : " + this.obj.Height + "\n";

        return str;
    },

    RenderWidget: function(content) {
        WriteHistory("RenderWidget: " + this.id + ":" + this.obj.Title);
        var xmlDoc = null;
        try //Internet Explorer
      {
            xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async = false;
            xmlDoc.loadXML(content);
        }
        catch (e) {
            try //Firefox, Mozilla, Opera, etc.
         {
                parser = new DOMParser();
                xmlDoc = parser.parseFromString(content, "text/xml");
            }
            catch (e) { alert(e.message) }
        }

        if (xmlDoc.childNodes.length > 0) {
            //load the java script
            this.src = xmlDoc.getElementsByTagName("Script")[0].firstChild.nodeValue;
            installScriptSrc(this.src);

            //grab the widget content
            grabContent(xmlDoc.getElementsByTagName("Content")[0].firstChild.nodeValue + "?id=" + this.id, Function.createDelegate(this, this.onContentLoad));

            //set the script variable
            //add a quick reference to the widget objecct
            this.code = "var W{0}=myTabs.FindTab(" + this.Tab.id + ").FindWidget({0});";
            this.code += xmlDoc.getElementsByTagName("Initialization")[0].firstChild.nodeValue;
            this.code = this.code.replace(/\{0\}/g, this.id);
            //WriteHistory(code);
        }

        //nullify the object
        xmlDoc = null;
    },

    onContentLoad: function(content) {
        //need to ensure that the script code is loaded
        this.HTML = content;
        WriteHistory("<hr>Widget " + this.id + '<br>' + this.HTML + "<hr>");
        this.DoLoad();
    },

    DoLoad: function() {
        WriteHistory("DoLoad: " + this.id);
        if (installScriptSrc_CheckLoaded(this.src)) {
            installScript(this.code);
        }
        else {
            //if not loaded, check back again in 1 sec
            if (this.DoLoad_Idx)
                this.DoLoad_Idx++;
            else
                this.DoLoad_Idx = 1;

            if (this.DoLoad_Idx < 10)
                setTimeout(Function.createDelegate(this, this.DoLoad), 1000);
        }
    },

    Delete: function(instance) {
        if (myTabs.hasRequiredTabPermission(this.Tab, TabAccessLevel.Widget_Delete)) {
            if (confirm("Are you sure you want to delete the " + this.obj.Title.replace("\"", "\\\"") + " widget?")) {
                //Remove the widget from the list
                instance.WidgetDiv.parentNode.removeChild(instance.WidgetDiv);

                //Reorder the widgets in the page
                var col = this.obj.ColumnNo;
                var Widgets = this.Tab.Widgets;
                var spliceIdx = -1;
                var OrderStr = "";
                for (var i = 0; i < Widgets.length; i++) {
                    if (Widgets[i].obj.ColumnNo == col) {
                        if (Widgets[i].id == this.id) {
                            spliceIdx = i;
                        }
                        else if (Widgets[i].obj.OrderNo > this.obj.OrderNo) {
                            Widgets[i].obj.OrderNo = Widgets[i].obj.OrderNo - 1;
                        }
                        //widgets in the same column
                    }
                }

                WriteHistory("Delete: " + spliceIdx + ":");
                if (spliceIdx > -1) {
                    //Remove the widget from the tab array
                    Widgets.splice(i, 1);

                    //Remove the instance object from the widget instance array
                    myWidgets.RemoveWidgetInstance(instance.id);

                    instance = null;
                }

                //Programatically delete the widget
                JSON.Widget_Delete(this.Tab.id, this.id, myTabs.ReloadCurrentTab);
            }
        }
        else {
            alert("You do not have the permission to delete this widget");
        }
    },

    InstanceEdit: function(objToFocus, WidgetDiv_BodySettings, WidgetDiv_BodyContent, WidgetDiv_Command_Edit) {
        if (myTabs.hasRequiredTabPermission(this.Tab, TabAccessLevel.Widget_Edit)) {
            if (!WidgetDiv_BodyContent)
                WidgetDiv_BodyContent = this.instance.WidgetDiv_BodyContent;

            if (!WidgetDiv_BodySettings)
                WidgetDiv_BodySettings = this.instance.WidgetDiv_BodySettings;

            if (!WidgetDiv_Command_Edit)
                WidgetDiv_Command_Edit = this.instance.WidgetDiv_Command_Edit;

            WidgetDiv_BodySettings.style.display = "none";
            WidgetDiv_BodyContent.style.display = "none";
            if (this.instance.inEditMode) {
                WidgetDiv_BodyContent.style.display = "";
                WidgetDiv_Command_Edit.innerHTML = "Edit Widget Properties";
            }
            else {
                WidgetDiv_BodySettings.style.display = "";
                WidgetDiv_Command_Edit.innerHTML = "Cancel Edit";
            }
            this.instance.inEditMode = !this.instance.inEditMode;

            if (objToFocus)
                $show(objToFocus, "IGNORE", true);
        }
        else {
            alert("You do not have permission to edit the widget properties");
        }
    },

    InstanceLoad: function() {
        WriteHistory("InstanceLoad:" + this.id + ":" + this.obj.Title);
        var RenderInColumn = null;
        switch (this.obj.ColumnNo) {
            case 2:
                RenderInColumn = this.Tab.Element_Cell2;
                if (RenderInColumn == null)
                    return;
                break;
            case 3:
                RenderInColumn = this.Tab.Element_Cell3;
                if (RenderInColumn == null)
                    return;
                break;
            case 4:
                RenderInColumn = this.Tab.Element_Cell4;
                if (RenderInColumn == null)
                    return;
                break;
            default:
                RenderInColumn = this.Tab.Element_Cell1;
                break;
        }

        var WidgetDiv = document.createElement("div");
        WidgetDiv.className = "widget";
        WidgetDiv.id = "wdiv_" + this.id;
        var theContent = this.HTML.replace(/\{0\}/g, this.id).replace("[img]", this.obj.Icon).replace("[title]", this.obj.Title);
        var idx_Menu = theContent.indexOf("<!-- MENU -->");
        var theMenu = theContent.substring(idx_Menu);
        var theContent = theContent.substring(0, idx_Menu);
        WidgetDiv.innerHTML = theContent;

        /*
        Need to render in the correct order
        to do that, i need to search the tab -> which takes very long
        so do a hack, use myWidgets.GetWidgetInstance(id)
        wdiv_xxx
        RenderInColumn would have childnodes, so i loop thru renderincolumn childnodes,
        get the matching order then insert accordingly
        */

        if (RenderInColumn.childNodes.length < 1) {
            RenderInColumn.appendChild(WidgetDiv);
        }
        else {
            var Inserted = false;

            for (var i = 0; i < RenderInColumn.childNodes.length && !Inserted; i++) {
                var theDivId = RenderInColumn.childNodes[i].id;
                if (theDivId.length > 5) {
                    var WidgetInstanceID = parseInt(theDivId.substring(5));
                    //must be int based on the format
                    if (WidgetInstanceID > 0) {
                        var theWidgetInstance = $WI(WidgetInstanceID);
                        if (theWidgetInstance) {
                            if (this.obj.OrderNo < theWidgetInstance.Widget.obj.OrderNo) {
                                //since order no is incremental, lesser means insert there
                                RenderInColumn.insertBefore(WidgetDiv, RenderInColumn.childNodes[i]);
                                Inserted = true;
                                break;
                            }
                        }
                        else {
                            WriteHistory("Cannot find Widget Instance");
                        }
                    }
                }
            }

            if (!Inserted)
                RenderInColumn.appendChild(WidgetDiv);
        }
        /*
        if (RenderInColumn.childNodes.length <= this.obj.OrderNo)
        {
        RenderInColumn.appendChild(WidgetDiv);
        }
        else
        {
        RenderInColumn.insertBefore(WidgetDiv, RenderInColumn.childNodes[this.obj.OrderNo-1]);
        }
        */

        var theMenuNode = document.createElement("div");
        theMenuNode.id = "WTab_" + this.Tab.id + "_" + this.id;
        theMenuNode.innerHTML = theMenu;
        div_Widgets.appendChild(theMenuNode);

        var MenuElements = theMenuNode.getElementsByTagName("LI");
        WriteHistory("MenuElements: " + MenuElements.length);

        for (var i = 0; i < MenuElements.length; i++) {
            var found = false;
            if (this.instance.Menu_Edit) {
                for (var j = 0; j < this.instance.Menu_Edit.length; j++) {
                    WriteHistory("Compare:" + this.instance.Menu_Edit[j] + " : " + MenuElements[i].id);
                    if (this.instance.Menu_Edit[j] == MenuElements[i].id) {
                        found = true;
                        if (!this.Tab.hasRequiredTabPermission(TabAccessLevel.Widget_Edit)) {
                            MenuElements[i].style.display = "none";
                        }
                    }
                }
            }

            if (!found) {
                if (MenuElements[i].childNodes && MenuElements[i].childNodes.length > 0 && MenuElements[i].childNodes[0].onclick) {
                    var onClickCmd = MenuElements[i].childNodes[0].onclick.toString().toLowerCase();
                    WriteHistory("MenuElements #" + i + "<br>" + onClickCmd);
                    WriteHistory(onClickCmd.indexOf(".titleedit()"));
                    if (onClickCmd.indexOf(".titleedit()") > -1) {
                        if (!this.Tab.hasRequiredTabPermission(TabAccessLevel.Widget_EditTitle)) {
                            MenuElements[i].style.display = "none";
                        }
                    }
                    else if (onClickCmd.indexOf(".delete()") > -1) {
                        if (!this.Tab.hasRequiredTabPermission(TabAccessLevel.Widget_Delete)) {
                            MenuElements[i].style.display = "none";
                        }
                    }
                    else if (onClickCmd.indexOf(".edit()") > -1) {
                        if (!this.Tab.hasRequiredTabPermission(TabAccessLevel.Widget_Edit)) {
                            MenuElements[i].style.display = "none";
                        }
                    }
                }
            }
        }

        //installScript("Menu_AddTarget('wdivca" + this.id + "','wdivcd" + this.id + "');");
        installScript("Menu_AddTarget('wdivcad" + this.id + "','wdivcd" + this.id + "');");

        //Get the Widget box elements
        this.instance.WidgetDiv_Footer = document.getElementById("wdivf" + this.id);
        this.instance.WidgetDiv_Footer.className = (this.obj.Expanded ? "widget_footer_collapse" : "widget_footer_expand");

        //compulsory fields      
        this.instance.WidgetDiv = WidgetDiv;
        this.instance.WidgetDiv_Body = document.getElementById("wdivb" + this.id);

        if (this.obj.Height > 0) {
            this.instance.WidgetDiv_Body.style.height = this.obj.Height + "px";
        }

        if (!this.obj.Expanded)
            this.instance.WidgetDiv_Body.style.display = "none";

        this.instance.WidgetDiv_Header_Lbl = document.getElementById("wdivht" + this.id);
        this.instance.WidgetDiv_Header_Input = document.getElementById("wdivhi" + this.id);
        if (myTabs.hasRequiredTabPermission(this.Tab, TabAccessLevel.Widget_EditTitle)) {
            var script = "$('" + this.instance.WidgetDiv_Header_Input.id + "').onblur = function(){$WI('" + this.id + "').SaveTitle();};";
            if (is_ie)
                script += "$('" + this.instance.WidgetDiv_Header_Input.id + "').onkeypress = function(){if(event.keyCode==13){$WI('" + this.id + "').SaveTitle();event.keyCode=0;return false;}};";
            else
                script += "$('" + this.instance.WidgetDiv_Header_Input.id + "').onkeypress = function(event){if(event.keyCode==13){$WI('" + this.id + "').SaveTitle();return false;}};";
            installScript(script);
        }
    },

    InstanceLoadComplete: function() {
        if (myTabs.hasRequiredTabPermission(this.Tab, TabAccessLevel.Widget_Reorder)) {
            myTabs.EnableWidgetDragDrop(this.Tab, this.obj.ColumnNo);
        }
        this.loaded = true;

        //hide the ajax bar when at least one widget is rendered
        div_WidgetProgress.style.display = "none";

        WriteHistory("InstanceLoadComplete:" + this.instance.WidgetDiv.id + ":" + this.instance.WidgetDiv.parentNode);
        this.instance.WidgetDiv = $get(this.instance.WidgetDiv.id);
    },

    InstanceToggleExpand: function(WidgetDiv_Footer, WidgetDiv_Body) {
        if (!WidgetDiv_Footer)
            WidgetDiv_Footer = this.instance.WidgetDiv_Footer;

        if (!WidgetDiv_Body)
            WidgetDiv_Body = this.instance.WidgetDiv_Body;

        if (this.obj.Expanded) {
            //collapse it
            WidgetDiv_Footer.className = "widget_footer_expand";
            this.obj.Expanded = false;
            Effect.BlindUp(WidgetDiv_Body);
        }
        else {
            //expand it
            WidgetDiv_Footer.className = "widget_footer_collapse";
            this.obj.Expanded = true;
            Effect.BlindDown(WidgetDiv_Body);
        }

        if (this.Tab.hasRequiredTabPermission(TabAccessLevel.Widget_Edit)) {
            JSON.Widget_UpdateProperty(this.Tab.id, this.id, "Expanded", this.obj.Expanded);
        }
    },

    InstanceTitleEdit: function(WidgetDiv_Header_Lbl, WidgetDiv_Header_Input) {
        if (myTabs.hasRequiredTabPermission(this.Tab, TabAccessLevel.Widget_Edit)) {
            if (!WidgetDiv_Header_Lbl)
                WidgetDiv_Header_Lbl = this.instance.WidgetDiv_Header_Lbl;

            if (!WidgetDiv_Header_Input)
                WidgetDiv_Header_Input = this.instance.WidgetDiv_Header_Input;

            WidgetDiv_Header_Lbl.style.display = "none";
            WidgetDiv_Header_Input.style.display = "none";

            if (this.instance.inTitleEditMode) {
                WidgetDiv_Header_Lbl.style.display = "";
            }
            else {
                WidgetDiv_Header_Input.value = WidgetDiv_Header_Lbl.innerHTML;
                $show(WidgetDiv_Header_Input.id, "inline", true);
            }
            this.instance.inTitleEditMode = !this.instance.inTitleEditMode;
        }
    },

    InstanceSaveTitle: function(WidgetDiv_Header_Lbl, WidgetDiv_Header_Input) {
        if (myTabs.hasRequiredTabPermission(this.Tab, TabAccessLevel.Widget_EditTitle)) {
            if (!WidgetDiv_Header_Lbl)
                WidgetDiv_Header_Lbl = this.instance.WidgetDiv_Header_Lbl;

            if (!WidgetDiv_Header_Input)
                WidgetDiv_Header_Input = this.instance.WidgetDiv_Header_Input;


            if (WidgetDiv_Header_Input.value != WidgetDiv_Header_Lbl.innerHTML) {
                JSON.Widget_UpdateProperty(this.Tab.id, this.id, 'Title', WidgetDiv_Header_Input.value);
                WidgetDiv_Header_Lbl.innerHTML = WidgetDiv_Header_Input.value;
            }
            this.instance.inTitleEditMode = true;
            this.instance.TitleEdit();
        }
        else {
            alert("You do not have permission to edit the widget title");
        }
    }
}

WidgetInstance = function(WidgetObj)
{
   /*
   this.Widget = WidgetObj;
   this.id = this.Widget.id;
   this.inEditMode = false;
   this.inTitleEditMode = false;
   WidgetObj.instance = this;
   this.Load();
   */
}

WidgetInstance.prototype = 
{
   initializeBase : function(WidgetObj)
   {
      this.Widget = WidgetObj;
      this.id = this.Widget.id;
      this.inEditMode = false;
      this.inTitleEditMode = false;
      WidgetObj.instance = this;
      this.Load();   
   },

   Edit : function()
   {
      this.Widget.InstanceEdit();
   },
   
   Save : function()
   {
      this.Widget.Save();
   },
   
   Load : function()
   {
      this.Widget.InstanceLoad();
      
      this.Widget.InstanceLoadComplete();
   },

   ToggleExpand : function()
   {
      this.Widget.InstanceToggleExpand();
   },
   
   Expand : function()
   {
      this.Widget.obj.Expanded = false;
      this.Widget.InstanceToggleExpand();
   },
   
   Collapse : function()
   {
      this.Widget.obj.Expanded = true;
      this.Widget.InstanceToggleExpand();
   },
   
   Delete : function()
   {
      this.Widget.Delete(this);
   },
   
   TitleEdit : function()
   {
      this.Widget.InstanceTitleEdit();
   },
   
   SaveTitle : function()
   {
      this.Widget.InstanceSaveTitle();
   },
   
   SaveHeight : function(theHeight)
   {
     JSON.Widget_UpdateProperty(this.Widget.Tab.id, this.id, 'height', parseInt(theHeight));
     this.Widget.obj.Height = theHeight;
   },
   
   ResetHeight : function()
   {
     JSON.Widget_UpdateProperty(this.Widget.Tab.id, this.id, 'height', parseInt(0));
   },

   InstanceRefresh : function()
   {
      var theDiv = $get(this.WidgetDiv.id);
      theDiv.parentNode.removeChild(theDiv);
      grabContent(this.Widget.obj.URL, Function.createDelegate(this.Widget, this.Widget.RenderWidget));
   },
   
   Refresh : function()
   {
      this.InstanceRefresh();
   }
}


//this one has all the functions for widgets
_myWidgets = function()
{
   this.WidgetInstances = new Array();     
}

_myWidgets.prototype =
{
    toString: function() {
        for (var i = 0; i < this.WidgetInstances.length; i++) {
            var wi = this.WidgetInstances[i];
            WriteHistory(i + ": Tab #" + wi.Widget.Tab.id + ": Widget #" + wi.id + ": Col #" + wi.Widget.obj.ColumnNo + " : Order #" + wi.Widget.obj.OrderNo + " : Title : " + wi.Widget.obj.Title);
        }
    },

    AddWidgetInstance: function(obj) {
        this.WidgetInstances.push(obj);
    },

    GetWidgetInstance: function(id) {
        for (var i = 0; i < this.WidgetInstances.length; i++) {
            if (this.WidgetInstances[i].id == id) {
                return this.WidgetInstances[i];
            }
        }

        return null;
    },

    RemoveWidgetInstance: function(id) {
        if (myTabs.hasRequiredTabPermission(null, TabAccessLevel.Widget_Delete)) {
            for (var i = 0; i < this.WidgetInstances.length; i++) {
                if (this.WidgetInstances[i].id == id) {
                    if (this.WidgetInstances[i].Widget.Tab.Widgets.length < 2) {
                        //no more widgets left on page
                        ShowNoWidget();
                    }

                    this.WidgetInstances.splice(i, 1);
                    return;
                }
            }
        }

        return null;
    },

    GenerateForTab: function(theTab) {
        if (theTab.Widgets.length > 0) {
            this.GenerateTabWidgets(theTab);
        }
        else {
            JSON.Tab_GetWidgets(theTab.id, Function.createDelegate(this, this.Tab_GetWidgets));
        }
    },

    Tab_GetWidgets: function(obj) {
        var hasWidgets = false;
        if (obj) {
            var theTab = myTabs.FindTab(obj.TabID);

            if (theTab) {
                if (obj.Widgets) {
                    theTab.Widgets = new Array();
                    for (var i = 0; i < obj.Widgets.length; i++) {
                        hasWidgets = true;
                        theTab.Widgets.push(new _Widget(obj.Widgets[i], theTab));
                    }

                    WriteHistory("Tab_GetWidgets:#Widgets:" + theTab.Widgets.length);
                    this.GenerateTabWidgets(theTab);
                }
            }
        }

        if (!hasWidgets) {
            //no widgets, clear out the ajax bar
            //show the progress bar during loading
            div_WidgetProgress.style.display = "none";
            ShowNoWidget()
        }
    },

    AddWidget: function(WidgetId) {
        if (myTabs.hasRequiredTabPermission(null, TabAccessLevel.Tab_AddWidgets)) {
            var theTab = myTabs.GetCurrentTab();
            JSON.Tab_AddWidget(theTab.id, WidgetId, Function.createDelegate(this, this.Tab_AddWidgets));
        }
    },

    AddRSS: function(URL) {
        if (myTabs.hasRequiredTabPermission(null, TabAccessLevel.Tab_AddWidgets)) {
            var theTab = myTabs.GetCurrentTab();
            JSON.Tab_AddRSSWidget(theTab.id, URL, Function.createDelegate(this, this.Tab_AddWidgets));
        }
    },

    Tab_AddWidgets: function(obj) {
        if (myTabs.hasRequiredTabPermission(null, TabAccessLevel.Tab_AddWidgets)) {
            if (obj) {
                var theTab = myTabs.GetCurrentTab();

                if (theTab) {
                    var theWidget = new _Widget(obj, theTab);

                    var ary = theTab.Widgets;
                    for (var i = 0; i < ary.length; i++) {
                        if ((ary[i].obj.ColumnNo == obj.ColumnNo && ary[i].obj.OrderNo >= obj.OrderNo)) {
                            //increment existing order numbers
                            ary[i].obj.OrderNo += 1;
                        }
                    }
                    theTab.Widgets.push(theWidget);
                    this.SortWidgetArray(theTab);

                    WriteHistory("Tab_GetWidgets:#Widgets:" + theTab.Widgets.length);
                    this.GenerateTabWidget(theWidget);
                }
            }
        }
    },

    GenerateTabWidget: function(theWidget) {
        HideNoWidget();
        grabContent(theWidget.obj.URL, Function.createDelegate(theWidget, theWidget.RenderWidget));
    },

    GenerateTabWidgets: function(theTab) {
        //Clear out all the items
        removeChildNodes(theTab.Element_Cell1);
        removeChildNodes(theTab.Element_Cell2);
        removeChildNodes(theTab.Element_Cell3);
        if (theTab.Element_Cell4)
            removeChildNodes(theTab.Element_Cell4);

        var theWidgets = theTab.Widgets;
        this.SortWidgetArray(theTab);
        for (var i = 0; i < theWidgets.length; i++) {
            this.GenerateTabWidget(theWidgets[i]);
        }
    },

    SortWidgetArray: function(Tab) {
        var ary = Tab.Widgets;
        for (var i = 0; i < ary.length; i++) {
            for (var j = i + 1; j < ary.length; j++) {
                if ((ary[i].obj.ColumnNo < ary[j].obj.ColumnNo) ||
                (ary[i].obj.ColumnNo == ary[j].obj.ColumnNo && ary[i].obj.OrderNo < ary[j].obj.OrderNo)
               ) {
                    var t = ary[i];
                    ary[i] = ary[j];
                    ary[j] = t;
                }
            }
        }

        /*
        for(var i=0;i<ary.length;i++)
        {
        WriteHistory(ary[i].id + " : " + ary[i].obj.Title + " : " + ary[i].obj.ColumnNo + " : " + ary[i].obj.OrderNo);
        }
        */
    }
}

var myWidgets = new _myWidgets();

function $WI(id)
{
   return myWidgets.GetWidgetInstance(id);
}